import 'dart:convert';

import 'package:mediapipe_task_vision_example/util/p2p_socket.dart';

class P2PConnection implements SocketListener {
  P2PSocket? _socket;
  final String ip;

  P2PConnection(this.ip) {
    _socket = P2PSocket();
    _socket!.listener = this;
  }

  void connect() {
    String url = 'http://$ip:8081/websocket';
    _socket!.connect(url);
  }

  close() {
    if (_socket != null) {
      _socket!.close();
    }
  }

  send(data) {
    _socket!.send(jsonEncode(data));
  }

  @override
  void onClose(int? code, String? reason) {
    print('服务端关闭Socket [$code => $reason]!');
  }

  @override
  void onMessage(msg) {
    print('接收数据: ' + msg.toString());
    //处理消息
  }

  @override
  void onOpen() {
    print('onOpen');
  }
}
